﻿using System;
using System.Text.RegularExpressions;
using System.Web.Security;
using System.Windows;
using System.Windows.Input;
using CCSManager.CCS;
using CCSManager.Properties;
using MembershipUser = CCSManager.CCS.MembershipUser;

namespace CCSManager
{
    /// <summary>
    /// Interaction logic for Login.xaml
    /// </summary>
    public partial class Login : Window
    {
        public Login()
        {
            InitializeComponent();

            this.Closed += new EventHandler(Login_Closed);
        }

        void Login_Closed(object sender, EventArgs e)
        {
            App.Current.Shutdown();
        }

        public event EventHandler Registered;

        private void CreateAccountButton_Click(object sender, RoutedEventArgs e)
        {
            Cursor lastCursor = this.Cursor;
            try
            {
                this.Cursor = Cursors.Wait;
                if (NewPasswordText.Password != ConfirmNewPasswordText.Password)
                {
                    throw new MembershipCreateUserException("Password and Confirm Password must match");
                }
                var webService = new CCS.CCS();
                var paymentSettings = new CCSPaymentSettings
                                          {
                                              Payment_URL = Settings.Default.PaymentURL,
                                              PayPal_AccountEmail = NewEmailText.Text,
                                              PayPal_cancelURL = string.Empty,
                                              PayPal_currencyCode = "USD",
                                              PayPal_includeNote = false,
                                              PayPal_ItemNumber = Guid.NewGuid().ToString(),
                                              PayPal_logoURL = string.Empty,
                                              PayPal_noteTitle = string.Empty,
                                              PayPal_notifyURL = Settings.Default.PaymentNotifyURL,
                                              PayPal_Quantity = 1,
                                              PayPal_requireShippingAddress = false,
                                              PayPal_successUrl = string.Empty,
                                              PayPal_tag = string.Empty,
                                              Timestamp = DateTime.Now
                                          };
                MembershipUser membershipUser = webService.CreateUser(NewUserNameText.Text, NewPasswordText.Password, paymentSettings);
                if (membershipUser != null)
                {
                    var ccsWebService = new CCS.CCS();
                    App.Credentials = new CCSCredentials { UserName = NewUserNameText.Text, Password = NewPasswordText.Password };
                    if (ccsWebService.ValidateUser(App.Credentials))
                    {
                        Guid providerUserKey = ccsWebService.GetProviderUserKey(NewUserNameText.Text, App.Credentials);
                        App.UserKey = providerUserKey;
                        App.DeveloperTokens = ccsWebService.GetDevToken(App.UserKey, App.Credentials);
                        var db = new Dashboard() { Left = Left, Top = Top };
                        foreach (object window in App.Current.Windows)
                        {
                            ((Window)window).Hide();
                        }
                        db.Show();
                    }
                }
            }
            catch (Exception exception)
            {
                Match membershipExceptionMatch = Regex.Match(exception.Message, "(?<=System\\.Web\\.Security\\.MembershipCreateUserException\\:\\s).*\\.+");
                if (!string.IsNullOrEmpty(membershipExceptionMatch.Value))
                {
                    //informationTextBlock.Text = string.Format("There was an error in registration: {0}", membershipExceptionMatch.Value);
                    //informationTextBlock.Foreground = new SolidColorBrush(Color.FromRgb(255, 0, 0));
                }
            }
            finally
            {
                this.Cursor = lastCursor;
            }
        }

        private void LoginButton_Click(object sender, RoutedEventArgs e)
        {
            Cursor lastCursor = this.Cursor;
            try
            {
                this.Cursor = Cursors.Wait;
                var ccsWebService = new CCS.CCS();
                App.Credentials = new CCSCredentials { UserName = UserNameText.Text, Password = PasswordText.Password };
                if (ccsWebService.ValidateUser(App.Credentials))
                {
                    Guid providerUserKey = ccsWebService.GetProviderUserKey(UserNameText.Text, App.Credentials);
                    App.UserKey = providerUserKey;
                    App.DeveloperTokens = ccsWebService.GetDevToken(App.UserKey, App.Credentials);
                    var db = new Dashboard() { Left = Left, Top = Top };
                    foreach (object window in App.Current.Windows)
                    {
                        ((Window)window).Hide();
                    }
                    db.Show();
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                MessageBox.Show(string.Format("An error occured: {0}", ex.Message));
#endif
            }
            finally
            {
                this.Cursor = lastCursor;
            }
        }
    }
}